package dbgroup02.dao.db2;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import dbgroup02.bean.Ticket;
import dbgroup02.dao.TicketDao;

public class TicketDB2Dao implements TicketDao {

	private JdbcTemplate jdbcTemplate;

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	ParameterizedRowMapper<Ticket> getTicketMapper = new ParameterizedRowMapper<Ticket>() {
		@Override
		public Ticket mapRow(ResultSet resultSet, int arg1) throws SQLException {
			Ticket ticket = new Ticket();
			ticket.setIdTicket(resultSet.getInt(1));
			ticket.setPrice(resultSet.getString(2));
			ticket.setTravelAgency(resultSet.getString(3));
			ticket.setIdPayment(resultSet.getInt(4));
			ticket.setIdPassenger(resultSet.getInt(5));
			return ticket;
		}
	};

	@Override
	@Transactional(readOnly = true, propagation = Propagation.REQUIRED)
	public Ticket getTicket(int idTicket) {
		List<Ticket> result = jdbcTemplate.query("SELECT * FROM "
				+ TicketDao.SCHEMA + ".TICKET WHERE TICKET_ID = ?",
				new Object[] { idTicket }, getTicketMapper);

		if (result.size() > 0)
			return result.get(0);
		else
			return null;
	}
}
